#!/usr/bin/perl

use strict;
use POSIX; 

my $script_name = "";
my @type = ();
my $time_interval = "";
my $logfile = "";

while ( @ARGV ) { # parse command line args
    $_ = shift @ARGV;
        if ( s/^--script_name=// ) {
	    $script_name = $_;
	}
        elsif ( s/^--time_interval=// ) {
	    $time_interval = $_;
	}
        elsif ( s/^--type=// ) {
	    @type = split(/,/, $_);
	}
	elsif ( s/^--help// ) {
	    &usage();
	    exit 0; 
	}
	else {
	    $logfile = $_;
	}
}	    


sub usage {
    print "usage:  ";
    print "log_parser.pl [<key>=<value>] <logfile>\n";
    print "keys:\n";
    print "--script_name\n";
    print "--time_interval\n";
    print "--type:\n";
    print "\t INF\n";
    print "\t WARN\n";
    print "\t ERR\n";
    print "\t STDOUT\n";
    print "\t STDERR\n";
    print "\t START\n";
    print "\t STOP\n";
}

sub print_args {
    print "script_name = ", $script_name, "\n" if $script_name;
    print "time_interval = ", $time_interval, "\n" if $time_interval;
    print "type = " if @type;
    foreach (@type) {
        print $_, " ";
    }
    print "\n" if @type;
    print "logfile = ", $logfile, "\n" if $logfile
}

if (! $logfile) {
    print "unknown logfile\n";
    &usage();
    exit 1;
}
if (! -r $logfile) {
    print "not exist file $logfile\n";
    exit 1;
}
open FILEIN, "<$logfile";

#current date
my ($sec, $min, $hour, $mday, $mon, $year) = (localtime)[0,1,2,3,4,5];

my $id;
#first go
while (<FILEIN>) {
    my ($cid, $cdate, $ctime, $ctype, $cscript_name, $crow_num, $chost) = split (/ /, $_);
    next if !( $ctype eq "STOP" );
    next if ( $script_name && $script_name ne $cscript_name ); 
    if ( "$cdate $ctime" =~ /^(.{4})\.(.{2})\.(.{2})\ (.{2})\:(.{2})\:(.{2})/ ) {
	my $yyyy = $1;
	my $mm = $2;
	my $dd = $3;
	my $H = $4;
	my $M = $5;
	my $S = $6;
	my $diff = difftime( mktime($sec,$min,$hour,$mday,$mon,$year), mktime($S,$M,$H,$dd,$mm-1,$yyyy-1900) );
	$id = $cid if ( !$time_interval || $diff < $time_interval );
    }
}
close FILEIN;

exit 0 if !($id);

#second go
open FILEIN, "<$logfile";
while (<FILEIN>) {
    next if !(/^$id/);
    my ($cid, $cdate, $ctime, $ctype, $cscript_name, $crow_num, $chost) = split (/ /, $_);
    my $flag="";
    foreach (@type) {
	$flag="OK" if ($_ eq $ctype);
    }
    next if ( @type && $flag ne "OK" ); 
    s/^[0-9]+\ //;
    print $_;
}

close FILEIN;
